<template>
  <PageContainer title="更换头像">
    <el-upload
      ref="upLoadRef"
      :auto-upload="false"
      class="avatar-uploader"
      :show-file-list="false"
      :on-change="onSelectFile"
    >
      <img v-if="imgUrl" :src="imgUrl" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>

    <el-button
      type="primary"
      :icon="Plus"
      size="large"
      @click="upLoadRef.$el.querySelector('input').click()"
      >选择图片</el-button
    >
    <el-button
      type="success"
      :icon="Upload"
      size="large"
      @click="onUpdateAvatar"
      >上传图片</el-button
    >
  </PageContainer>
</template>
<script lang="ts" setup name="">
import { ref } from 'vue'
import { Plus, Upload } from '@element-plus/icons-vue'
import PageContainer from '@/components/PageContainer.vue'
import { useUserStore } from '@/stores/user'
import { updateAvatarService } from '@/api/user'

const userStore = useUserStore()

// console.log(userStore.user.user_pic)

//基于store 接收的数据 初始化imgurl值
const imgUrl = ref(userStore.user.user_pic)

//点击 选择图片 按钮 触发 el-upload 组件的点击事件
const upLoadRef = ref()

//当 选中图片触发change事件 做页面预览 将本地图片转换为本地浏览路径
const onSelectFile = (uploadFile: any) => {
  // imgUrl.value = URL.createObjectURL(uploadFile.raw)

  //基于FileReader 读取图片做预览  并且其会返回base64编码
  const reader = new FileReader()
  reader.readAsDataURL(uploadFile.raw)
  reader.onload = () => {
    imgUrl.value = reader.result as string
  }
  // console.log(imgUrl.value)
}

const onUpdateAvatar = async () => {
  // console.log(imgUrl.value)

  const res = await updateAvatarService(imgUrl.value)
  //userStore  重新渲染 图片数据
  await userStore.getUser()
  //提示
  ElMessage.success(res.data.message)
}
</script>
<style scoped lang="scss">
.avatar-uploader {
  :deep() {
    .avatar {
      width: 278px;
      height: 278px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
      margin-bottom: 20px;
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 278px;
      height: 278px;
      text-align: center;
    }
  }
}
</style>
